const CDBSave = require('./dbsave');


class Address extends CDBSave.CDBSave{
    constructor(){
        super();
    }

    filePath(){
        return 'address_changda.json'
    }

    load(data){
        if(!data)return;

        this.notices = data;
    }

    save(){
        return this.notices;
    }

    getAddress(){
        return this.notices;
    }


    revise_address(message){
        let flag = 0;
        for(let i=0;i<this.notices.length;i++){
            if(this.notices[i].id == message.id){
                this.notices[i] = message;
                if(message.if_default){
                    flag = 1;
                }
                break;
            }
        }
        if(flag == 1){
            for(let j=0;j<this.notices.length;j++){
                if(this.notices[j].number == message.number && this.notices[j].id != message.id){
                    this.notices[j].if_default = false;
                }
            }
        }
    }

    add_address(newAddress){
        // console.log(newAddress)
        let id = this.notices.length + 1;
        newAddress.id = id;
        if(newAddress.if_default){
            for(let j=0;j<this.notices.length;j++){
                if(this.notices[j].number == newAddress.number && this.notices[j].id != newAddress.id){
                    this.notices[j].if_default = false;
                }
            }
        }
        let address = new Address_child(newAddress);
        this.notices.push(address);
    }


    remove_address(id,number){
        let flag = 0;
        for(let i=0;i<this.notices.length;i++){
            if(this.notices[i].id == id && this.notices[i].number == number){
                this.notices.splice(i,1);
                flag = 1;
                break;
            }
        }

        if(flag == 1){
            for(let i=0;i<this.notices.length;i++){
                this.notices[i].id = i+1;
            }
        }
    }
}



class Address_child{
    constructor(add_address){
        this.load(add_address)
    }

    load(data){
        this.id = data.id;
        this.number = data.number;
        this.name = data.name;
        this.telephone_number = data.telephone_number;
        this.address = data.address;
        this.if_default = data.if_default;
        this.give_position = data.give_position;
    }


    save(){
        return{
            id:this.id,
            number:this.number,
            name:this.name,
            telephone_number:this.telephone_number,
            address:this.address,
            if_default:this.if_default,
            give_position:this.give_position
        }
    }
}


module.exports = {Address,Address_child}